package br.usp.ime.dojo.core.repositories.impl.db;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import br.usp.ime.dojo.core.entities.User;
import br.usp.ime.dojo.core.exceptions.DuplicatedUserException;
import br.usp.ime.dojo.core.repositories.UserRepository;

public class UserRepositoryInDB implements UserRepository {
	
	private static UserRepositoryInDB instance = null;
	
	public static UserRepositoryInDB getInstance() {
		if (instance == null) {
			instance = new UserRepositoryInDB();
		}
		return instance;
	}
	
	public void add(User user) throws DuplicatedUserException {
		PersistenceManager persistenceManager = DojoPersistenceManagerFactory.get();
		try {
			persistenceManager.makePersistent(user);
		} finally {
			persistenceManager.close();
		}
	}

	public void clearAll() {
		PersistenceManager persistenceManager = DojoPersistenceManagerFactory.get();
		(persistenceManager.newQuery("delete * from User")).execute();
	}

	@SuppressWarnings("unchecked")
	public int count() {
		PersistenceManager persistenceManager = DojoPersistenceManagerFactory.get();
		Query query = persistenceManager.newQuery("select * from User");
		return ((List<User>)query.execute()).size();
	}

	public User get(String userName) {
		return (User) DojoPersistenceManagerFactory.get().getObjectById(User.class, userName);
	}

	public void remove(String userName) {
		PersistenceManager persistenceManager = DojoPersistenceManagerFactory.get();
		User user = (User) DojoPersistenceManagerFactory.get().getObjectById(User.class, userName);
		persistenceManager.deletePersistent(user);
	}

}
